package com.talent.proxy.mysql.common.packets.c2s;

import java.nio.ByteBuffer;

import com.talent.aio.common.ChannelContext;
import com.talent.proxy.mysql.common.Command;
import com.talent.proxy.mysql.common.MysqlExt;
import com.talent.proxy.mysql.common.MysqlPacket;
import com.talent.proxy.mysql.common.MysqlReturn;
import com.talent.proxy.mysql.common.utils.BufferUtil;

/**
 * 
 * <pre>
 *  Bytes                       Name
 *  -----                       ----
 *  1   (Length Coded Binary)   command 03
 *  string[EOF]                 the query the server shall execute
 * </pre>
 * @see http://dev.mysql.com/doc/internals/en/com-query.html
 */
public class QueryPacket extends MysqlPacket
{
	public byte command;
	public byte[] queryStr;

	public void decodeBody(ByteBuffer buffer, ChannelContext<MysqlExt, MysqlPacket, MysqlReturn> channelContext)
	{

		command = BufferUtil.read(buffer);
		queryStr = BufferUtil.readBytes(buffer);
	}

	public ByteBuffer encode(ChannelContext<MysqlExt, MysqlPacket, MysqlReturn> channelContext)
	{
		int bodySize = bodySize();
		ByteBuffer buffer = ByteBuffer.allocate(HEADER_SIZE + bodySize);
		BufferUtil.writeUB3(buffer, bodySize);
		buffer.put(seqId);
		buffer.put(Command.COM_QUERY);
		buffer.put(queryStr);
		return buffer;
	}

	@Override
	public int bodySize()
	{
		int size = 1;
		if (queryStr != null)
		{
			size += queryStr.length;
		}
		return size;
	}

	@Override
	protected String packetDesc()
	{
		return "MySQL Query Packet";
	}

	/** 
	 * @see com.talent.proxy.mysql.common.MysqlPacket#onReceived(com.talent.aio.common.ChannelContext)
	 * 
	 * @param channelContext
	 * @return
	 * @重写人: tanyaowu
	 * @重写时间: 2017年1月23日 下午5:00:26
	 * 
	 */
	@Override
	public MysqlReturn onReceived(ChannelContext<MysqlExt, MysqlPacket, MysqlReturn> channelContext)
	{
		// TODO Auto-generated method stub
		return null;
	}

}
